﻿using Data;
using DG.Tweening;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Level.Decorations
{
    public class ObstacleVisual : MonoBehaviour
    {
        private readonly List<Tween> _tweens = new();
        [SerializeField] private ObstacleHealth _health;
        private GameSceneData _data;

        public void Construct(GameSceneData data) =>
            _data = data;

        private void Start() =>
            _health.HealthDecreased += OnHealthChange;

        private void OnDestroy()
        {
            _health.HealthDecreased -= OnHealthChange;
            foreach (var tween in _tweens.Where(tween => tween != null)) 
                tween.Kill();
        }

        private void OnHealthChange()
        {
            var damageRatio = _health.Current / _health.Max;
            var tweenX = transform.DOScaleX(
                damageRatio,
                _data.CreateAnimationTime).SetEase(Ease.InBounce);
            _tweens.Add(tweenX);
            var tweenZ = transform.DOScaleZ(
                damageRatio,
                _data.CreateAnimationTime).SetEase(Ease.InBounce);
            _tweens.Add(tweenZ);
        }
    }
}